package com.example.mardan_demo1.interceptors;

import com.example.mardan_demo1.utils.JWTUtil;
import com.example.mardan_demo1.utils.ThreadLocalUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
/*拦截器代码*/
//拦截器注入到IOC容器里
@Component
public class LoginInterceptor implements HandlerInterceptor {
//    这是前置钩子，所有进来的请求都经过这个钩子
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String requestURI = request.getRequestURI();
    System.out.println("Intercepting request: " + requestURI);

    // 检查请求方法是否为 GET
    if ("GET".equalsIgnoreCase(request.getMethod())) {
        System.out.println("GET request detected, allowing request: " + requestURI);
        return true; // 直接放行 GET 请求
    }

    String token = request.getHeader("Authorization");
    if (request.getParameter("token") != null) {
        token = request.getParameter("token");
    }

    try {
        Map<String, Object> claims = JWTUtil.parseToken(token);
        ThreadLocalUtil.set(claims);
        System.out.println("Token valid, allowing request: " + requestURI);
        return true;
    } catch (Exception e) {
        response.setStatus(401);
        System.out.println("Invalid token for request: " + requestURI);
        return false;
    }
}

    //这是后置拦截钩子，请求结束了就执行这个
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        清空ThreadLocal数据，防止内存泄露
        ThreadLocalUtil.remove();
    }
}
